/**********************************************************************\

 Copyright 2012 Diggory Blake

 This file is part of klip-engine

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

\**********************************************************************/

#include "kmaterial.h"
#include "keffect.h"

kSharedResources<kMaterial> kMaterial::_sharedMaterials(0);

kMaterial* kMaterial::createShared(Container* container, const Key& key) {
	kMaterial* resource = new kMaterial();
	resource->setTexture(key);
	return resource;
}
void kMaterial::destroyShared(Container* container, kMaterial* resource) {
	delete resource;
}
kMaterial::kMaterial() {
	_effect = 0;
	for (size_t i = 0; i < 8; i++)
		_textures[i] = 0;
}
void kMaterial::setEffect(kEffect* effect, bool clearParams) {
	_effect = effect;
	if (clearParams) {
		_params.clear();
	} else {
		for (auto i = _params.begin(); i != _params.end(); i++) {
			i->second.handle = _effect->getParamHandle(i->first);
		}
	}
}
void kMaterial::setParam(const std::tstring& name, size_t n, const float* v) {
	EffectParam param;
	param.handle = _effect->getParamHandle(name);
	param.num = n;
	param.type = EPT_Float;
	for (size_t i = 0; i < n; i++)
		param.f[i] = v[i];

	_params[name] = param;
}
void kMaterial::setParam(const std::tstring& name, size_t n, const int* v) {
	EffectParam param;
	param.handle = _effect->getParamHandle(name);
	param.num = n;
	param.type = EPT_Integer;
	for (size_t i = 0; i < n; i++)
		param.i[i] = v[i];

	_params[name] = param;
}
void kMaterial::begin() const {
	for (auto i =_params.begin(); i != _params.end(); i++) {
		switch (i->second.type) {
		case EPT_Float:
			_effect->setParam(i->second.handle, i->second.num, i->second.f);
			break;
		case EPT_Integer:
			_effect->setParam(i->second.handle, i->second.num, i->second.i);
			break;
		}
	}
}
void kMaterial::end() const {
	for (auto i =_params.begin(); i != _params.end(); i++) {
		_effect->unsetParam(i->second.handle);
	}
}
